﻿using Conqueror.WP.Utility;
using Conqueror.WP.ViewModel.Games;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Telerik.Windows.Controls;

namespace Conqueror.WP.ViewModel
{
    public class MainPageViewModel : ViewModel
    {
        private Timer timer;
        private string username;
        private ObservableCollection<GameViewModel> games;
        private Visibility showError;
        private ObservableCollection<QuickActionViewModel> quickActions;

        public ObservableCollection<GameViewModel> Games
        {
            get { return games; }
            set
            {
                if (games != value)
                {
                    games = value;
                    Notify("Games");
                }
            }
        }

        public string Username
        {
            get { return username; }
            set
            {
                if (username != value)
                {
                    username = value;
                    Notify("Username");
                }
            }
        }

        public Orientation GamesOrientation
        {
            get
            {
                if (games.Count <= 3)
                    return Orientation.Horizontal;
                else return Orientation.Vertical;
            }
        }

        public Visibility ShowError
        {
            get { return showError; }
            set
            {
                if (showError != value)
                {
                    showError = value;
                    Notify("ShowError");
                }
            }
        }

        public ObservableCollection<QuickActionViewModel> QuickActions
        {
            get { return quickActions; }
            set
            {
                if (quickActions != value)
                {
                    quickActions = value;
                    Notify("QuickActions");
                }
            }
        }

        public MainPageViewModel()
        {
            this.QuickActions = new ObservableCollection<QuickActionViewModel>();
            for (int i = 0; i < 1; ++i)
            {
                AddQuickAction(new QuickActionViewModel(0)
                {
                    Background = new System.Windows.Media.SolidColorBrush(Colors.Blue),
                    Name = "Test 1"
                });
                AddQuickAction(new QuickActionViewModel(0)
                {
                    Background = new System.Windows.Media.SolidColorBrush(Colors.Red),
                    Name = "Test 2"
                });
                AddQuickAction(new QuickActionViewModel(0)
                {
                    Background = new System.Windows.Media.SolidColorBrush(Colors.Orange),
                    Name = "Test 3"
                });
                AddQuickAction(new QuickActionViewModel(0)
                {
                    Background = new System.Windows.Media.SolidColorBrush(Colors.Green),
                    Name = "Test 4"
                });
            }

            this.Games = new ObservableCollection<GameViewModel>();
            this.Games.CollectionChanged += (o, e) => { Notify("GamesOrientation"); };
            DownloadGameData(User.Username);

            timer = new Timer((o) =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    TimeSpan span = TimeSpan.FromSeconds(-1.0);
                    foreach (GameViewModel gvm in games)
                    {
                        gvm.Time = gvm.Time.Add(span);
                    }
                });
            }, null, 0, 1000);
            username = User.Username;
        }

        private async void DownloadGameData(string username)
        {
            try
            {
                List<API.Game> games = await Conqueror.API.Game.GetUserGames(User.Username, API.GameState.Active);
                games = games.Where(game => game.State == API.GameState.Active).ToList();

                List<GameViewModel> gvm = new List<GameViewModel>();
                foreach (var game in games)
                {
                    gvm.Add(new GameViewModel(game));
                }

                gvm = gvm.OrderBy(game => game.Time).ToList();
                gvm = gvm.OrderBy(game => (float)game.State).ToList();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.Games.Clear();
                    foreach (var game in gvm)
                    {
                        this.Games.Add(game);
                    }
                    Notify("Games");
                });

                if (games.Count == 0)
                    throw new Exception("No games exist for player");

                //Update Live Tile:
                ShellTile tile = ShellTile.ActiveTiles.First();
                LiveTileHelper.UpdateTile(tile, new RadIconicTileData() { Count = gvm.Where(game => game.State == API.GamePlayerState.Ready).Count() });

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ShowError = Visibility.Collapsed;
                });
            }
            catch (Exception e)
            {
                //Update Live Tile:
                ShellTile tile = ShellTile.ActiveTiles.First();
                LiveTileHelper.UpdateTile(tile, new RadIconicTileData() { Count = 0 });

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ShowError = Visibility.Visible;
                });
            }
        }

        private void AddQuickAction(QuickActionViewModel viewModel)
        {
            QuickActionViewModel vm = new QuickActionViewModel(QuickActions.Count)
            {
                Background = viewModel.Background,
                IsExpanded = viewModel.IsExpanded,
                Name = viewModel.Name
            };
            vm.Expanded += (o, e) =>
                {
                    if (e)
                    {
                        MoveQuickActions(vm.Index, vm.ExpandedIndex);
                    }
                    else
                    {
                        MoveQuickActions(vm.ExpandedIndex, vm.Index);
                    }
                };
            QuickActions.Add(vm);
        }

        private void MoveQuickActions(int from, int to)
        {
            QuickActionViewModel temp = QuickActions[from];
            QuickActions.Remove(temp);
            QuickActions.Insert(to, temp);
        }
    }
}
